<template>
  <div>
    <Breadcrumb :items="['系统管理', '字典管理']" />
    <a-card class="general-card" title="字典管理">
      <template #extra>
        <a-space direction="horizontal" :size="18">
          <a-button v-authorities="[SYS_PM.SYS_DICT_READ]" type="primary" :loading="loading" @click="refresh()">
            <template #icon>
              <icon-search />
            </template>
            搜索
          </a-button>
          <a-button>
            <template #icon>
              <icon-refresh />
            </template>
            重置
          </a-button>
        </a-space>
      </template>
      <a-form
        ref="dictSearchModel"
        :model="searchModel"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
        label-align="left"
      >
        <a-row :gutter="16">
          <a-col :xs="24" :sm="20" :md="12" :lg="8">
            <a-form-item field="name" label="字典名">
              <a-input
                v-model="searchModel.name"
                allow-clear
                placeholder="字典名"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="20" :md="12" :lg="8">
            <a-form-item field="code" label="字典编码">
              <a-input
                v-model="searchModel.code"
                allow-clear
                placeholder="字典编码"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>

      <!--分割线-->
      <a-divider direction="horizontal" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="16">
          <a-space>
            <a-button v-authorities="[SYS_PM.SYS_DICT_WRITE]" type="primary" @click="onCreate">
              <template #icon>
                <icon-plus />
              </template>
              添加
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="8" style="text-align: right">
          <a-button>
            <template #icon>
              <icon-download />
            </template>
            下载
          </a-button>
        </a-col>
      </a-row>

      <a-table
        :columns="tableColumns"
        :data="tbData"
        :loading="loading"
        row-key="id"
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"/>
    </a-card>

    <dict-drawer ref="dictDrawer" @refresh="refresh"/>
    <dict-item-drawer ref="dictItemDrawer"/>
  </div>
</template>

<script setup lang="tsx">
import { onMounted, ref } from 'vue'
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import DictDrawer from '@/views/system/dict/components/dict-drawer.vue'
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import DictItemDrawer from '@/views/system/dict/components/dict-item-drawer.vue'
import { PaginationProps } from '@arco-design/web-vue'
import useLoading from '@/hooks/loading'
import usePaging from '@/hooks/paging'
import { listWithPagination, deleteById } from '@/api/modules/system/dict'
import { DictParam, DictVo } from '@/types/modules/system'
import dayjs from 'dayjs'
import { SYS_PM } from '@/types/PM'

const tableColumns = [{
  title: '序号',
  dataIndex: 'id'
}, {
  title: "字典名",
  dataIndex: "name",
}, {
  title: '字典编码',
  dataIndex: 'code'
}, {
  title: '创建时间',
  render: ({ record }: { record: any }) => {
    return dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss')
  }
}, {
  title: '修改时间',
  render: ({ record }: { record: any }) => {
    return dayjs(record.updateTime).format('YYYY-MM-DD HH:mm:ss')
  }
}, {
  title: "操作",
  width: 330,
  align: "right",
  fixed: "right",
  render: ({ record }: { record: any }) => {
    return <>
      <a-button
        v-authorities={Array.of(SYS_PM.SYS_DICT_READ)}
        type="text"
        size="small"
        v-slots={{
          icon: () => <icon-drag-dot />,
          default: () => '字典项'
        }}
        onClick={() => onOpenDictItem(record.code, record.id)}
      >
        字典项
      </a-button>
      <a-button v-authorities={Array.of(SYS_PM.SYS_DICT_READ)} type="text" size="small" onClick={() => onPreview(record.id)}>
        预览
      </a-button>
      <a-button v-authorities={Array.of(SYS_PM.SYS_DICT_WRITE)} type="text" size="small" onClick={() => onUpdate(record.id)}>
        编辑
      </a-button>
      <a-popconfirm content={`确定删除 '${record.name}' 吗?`} type="warning" onOk={() => onDelete(record.id)}>
        <a-button v-authorities={Array.of(SYS_PM.SYS_DICT_WRITE)} type="text" size="small" status="danger">
          删除
        </a-button>
      </a-popconfirm>
    </>
  }
}]
const searchModel = ref<DictParam>({});
const tbData = ref<DictVo[]>([])
const dictDrawer = ref<any>(null)
const dictItemDrawer = ref<any>(null)
const { pageable, setPageable, prevPage } = usePaging();
const { loading, setLoading } = useLoading();
const pagination = ref<PaginationProps>({
  defaultCurrent: 1,
  defaultPageSize: 10
});

const onDelete = async (id: number) => {
  try {
    await deleteById(id);
    if (tbData.value.length <= 1) {
      prevPage();
    }
  } finally {
    await refresh();
  }
};

const onCreate = () => {
  dictDrawer.value.createHandle()
}

const onOpenDictItem = async (code: string, id: number) => {
  setLoading(true)
  await dictItemDrawer.value.openHandle(code, id)
  setLoading(false)
}
const onUpdate = async (id: number) => {
  setLoading(true)
  await dictDrawer.value.updateHandle(id)
  setLoading(false)
}

const onPreview = async (id: number) => {
  setLoading(true)
  await dictDrawer.value.previewHandle(id)
  setLoading(false)
}

const refresh = async () => {
  setLoading(true);
  const { data } = await listWithPagination(pageable.value, searchModel.value);
  pagination.value = {
    current: data.current,
    pageSize: data.size,
    total: data.total,
    showTotal: true,
    showPageSize: true
  };
  tbData.value = data.records;
  setLoading(false);
};

const onPageChange = (page: number) => {
  setPageable(page - 1, pageable.value.size);
  refresh();
};

const onPageSizeChange = (pageSize: number) => {
  setPageable(pageable.value.page, pageSize);
  refresh();
};


onMounted(() => {
  refresh()
})
</script>

<script lang="tsx">
export default {
  name: 'Dict'
}
</script>

<style scoped>

</style>
